import cv2



# 均值哈希算法
def aHash(img,xlcs):
    img2 = cv2.resize(img, (xlcs, xlcs), interpolation=cv2.INTER_CUBIC)
    gray = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)
    s = 0
    hash_str = ''
    # 遍历累加求像素和
    for i in range(xlcs):
        for j in range(xlcs):
            s = s + gray[i, j]
            # print(f'{i}/{j}')
    # 求平均灰度
    avg = s / (int(xlcs) * int(xlcs))
    # 灰度大于平均值为1相反为0生成图片的hash值
    for i in range(xlcs):
        for j in range(xlcs):
            if gray[i, j] > avg:
                hash_str = hash_str + '1'
            else:
                hash_str = hash_str + '0'
    return hash_str

# 差值感知算法
def dHash(img,xlcs,xlcsp):
    # 可以直接将数据流进行缩放大小。
    img2 = cv2.resize(img, (xlcsp, xlcs), interpolation=cv2.INTER_CUBIC)
    # 转换灰度图
    gray = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)
    hash_str = ''
    # 每行前一个像素大于后一个像素为1，相反为0，生成哈希
    for i in range(xlcs):
        for j in range(xlcs):
            if gray[i, j] > gray[i, j + 1]:
                hash_str = hash_str + '1'
            else:
                hash_str = hash_str + '0'
    return hash_str

# Hash值对比
def cmpHash(hash1, hash2):
    n = 0
    # hash长度不同则返回-1代表传参出错
    if len(hash1) != len(hash2):
        return -1
    # 遍历判断
    for i in range(len(hash1)):
        # 不相等则n计数+1，n最终为相似度
        if hash1[i] != hash2[i]:
            n = n + 1
    return n


if __name__ == '__main__':
    pass